/**
 * Copyright 2008 Mathias Doenitz, http://lis.to/
 *
 * This file is part of the lis.to java desktop client. The lis.to java desktop client is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * The lis.to java desktop client is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with the lis.to java desktop client.
 * If not, see http://www.gnu.org/licenses/
 */

package listo.client.model;

import com.thoughtworks.xstream.converters.SingleValueConverter;
import org.apache.commons.lang.StringUtils;

import java.security.SecureRandom;

/**
 * An immutable object id consisting of a randomly set 64 bit integer.
 */
public class ObjectId {

    private static SecureRandom secureRandom;

    private final long value;

    private ObjectId(long value) {
        this.value = value;
    }

    public ObjectId(ObjectId id) {
        this.value = id.value;
    }

    public ObjectId() {
        if (secureRandom == null) {
            secureRandom = new SecureRandom();
        }
        value = secureRandom.nextLong();
    }

    public int hashCode() {
        return ((Long) value).hashCode();
    }

    public boolean equals(Object obj) {
        return obj instanceof ObjectId && value == ((ObjectId) obj).value;
    }

    public String toString() {
        return StringUtils.leftPad(Long.toHexString(value), 16, '0');
    }

    public static ObjectId valueOf(String hexString) {
        if (hexString.length() != 16) throw new NumberFormatException();

        // we can't parse the long directly because in 50% of the cases it will
        // be > MAXLONG since it's unsigned
        // therefore we just chop the whole thing in two and bitshift the results to the right place
        long value = Long.parseLong(hexString.substring(0, 8), 16) << 32;
        value += Long.parseLong(hexString.substring(8, 16), 16);
        return new ObjectId(value);
    }

    /**
     * A simple xml converter using HEX values.
     */
    public static class Converter implements SingleValueConverter {

        public boolean canConvert(Class type) {
            return type == ObjectId.class;
        }

        public String toString(Object obj) {
            return obj.toString();
        }

        public Object fromString(String str) {
            return ObjectId.valueOf(str);
        }
    }
}
